package com.example.sina;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sina.base.BaseIRequestListener;
import com.example.sina.base.BaseUiListener;
import com.tencent.tauth.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

public class QQActivity extends Activity implements OnClickListener {

	private String appId = null;
	private String scope = "all";// 授权范围
	private Tencent tencent;
	private Button login, getUser;;
	private TextView text;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qq_activity);

		appId = getResources().getString(R.string.qq_app_id);
		tencent = Tencent.createInstance(appId, this.getApplicationContext());

		login = (Button) findViewById(R.id.qq_activity_login);// 授权 登录
		getUser = (Button) findViewById(R.id.qq_activity_userinfo);// 获取用户信息
		text = (TextView) findViewById(R.id.qq_activity_text);

		login.setOnClickListener(this);
		getUser.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.qq_activity_login: // 登录 授权
			if (!tencent.isSessionValid()) {
				@SuppressWarnings("unused")
				IUiListener listener = new BaseUiListener() {

					@Override
					public void onComplete(JSONObject result) {
						super.onComplete(result);
						text.setText(result.toString());

						// 获取openID
						tencent.requestAsync(Constants.GRAPH_OPEN_ID, null, Constants.HTTP_GET,
								new BaseIRequestListener("m_me", true) {

									@Override
									public void onComplete(JSONObject result, Object obj) {
										super.onComplete(result, obj);
										text.append("\n" + result.toString());
									}

								}, null);
					}
				};
				tencent.login(this, scope, listener); // 登录授权 认证
			} else {
				text.setText("loginc 错误");
			}
			break;
		case R.id.qq_activity_userinfo:// 获取用户信息
			if (ready()) {
				tencent.requestAsync(Constants.GRAPH_SIMPLE_USER_INFO, null, Constants.HTTP_GET,
						new BaseIRequestListener("get_simple_userinfo", false), null);
			}
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.v("sample", "onActivityResult:" + requestCode);
		tencent.onActivityResult(requestCode, resultCode, data);
	}

	private boolean ready() {
		boolean ready = tencent.isSessionValid() && tencent.getOpenId() != null;
		if (!ready)
			Toast.makeText(this, "login and get openId first, please!", Toast.LENGTH_SHORT).show();
		return ready;
	}
}
